# coding:utf8
import redis
import dbconf


bind_db = dbconf.getdb('bind') # phone to acid
wxsign_db = dbconf.getdb('wxsign') # acid to signinfo : {acid:{day：123}} 1 签到 2 签到领奖
wxbind_db = dbconf.getdb('wxbind') # openid to phone | phone to openid

def get_acid(phone):
    key = 'phone2acid' # 实际游戏中固定为 `bind`
    return bind_db.hget(key,phone)

def check_sign(acid, today):
    signed = wxsign_db.hget(key，today)
    if signed:
        return True
    return False

def sign2db(acid):
    key = acid
    today = time.time().getday()
    if check_sign(key, today):
        return False, None
    
    record = wxsign_db.hgetall(key，today)
    if wxsign_db.hset(key, today, 1):
        return True, len(record) + 1

def set_openid_phone(openid, phone):
    key = 'openid2phone'
    wxbind_db.hset(key, openid, phone)
    return True

def get_openid_phone(openid):
    key  = 'openid2phone'
    return wxbind_db.hget(key, openid)


def wxbind(openid,phone)
    '''绑定帐号请求
    '''
    if not openid or not phone:
        return 12 #errcode

    acid = get_acid(phone)
    if not acid:
        return 13 # 游戏未绑定手机号/帐号不存在 -- 返回提示到游戏中绑定手机号内容
    
    bindphone = get_openid_phone(openid)
    if bindphone:
        return bindphone #已经绑定手机号 --返回已经绑定页面

    # binding
    if set_openid_phone(openid, phone):
        return phone

def wxsign(openid):
    phone = get_openid_phone(openid)
    if not phone:
        return 18# 未绑定游戏，请先绑定游戏
    
    acid = get_acid(phone)
    if not acid:
        return 19 # 帐号不存在
    
    ok,nu = sign2db(acid)
    if not ok:
        return 20 # 不可重复签到
    
    if not eword(acid):
        return 21 # 签到奖励失败

    retrun "你已签累计{}天，获得500金币奖励！".format(nu)

    


def init():
    bind_db.hset('phonebind','1340172654','Aaa10087')
    bind_db.hset('phonebind','1340172656','Aaa10088')
    bind_db.hset('phonebind','1340172657','Aaa10089')
    bind_db.hset('phonebind','1340172658','Aaa10090')
    bind_db.hset('phonebind','1340172659','Aaa10081')
    bind_db.hset('phonebind','1340172660','Aaa10082')





